<template>
  <div class="update-password">
    <van-nav-bar
      title="修改密码"
      left-arrow
      :safe-area-inset-top="true"
      @click-left="onClickLeft"
    />
    <van-form @submit="onSubmit" style="margin-top: 2rem">
      <van-cell-group inset>
        <van-field
          v-model="oldPassword"
          type="password"
          name="旧密码"
          label="旧密码"
          placeholder="请输入旧密码"
          :rules="[{ required: true, message: '请填写旧密码！' }]"
        />
        <van-field
          v-model="newPassword"
          type="password"
          name="新密码"
          label="新密码"
          placeholder="请输入新密码"
          :rules="[{ required: true, message: '请填写新密码！' }, {validator, message: '密码必须以字母开头，长度在6-18位，且不弄包含特殊字符'}]"
        />
        <van-field
          v-model="confirmPassword"
          type="password"
          name="确认密码"
          label="确认密码"
          placeholder="请输入确认密码"
          :rules="[{ required: true, message: '请填写确认密码！' }, {validator, message: '密码必须以字母开头，长度在6-18位，且不弄包含特殊字符'}]"
        />
      </van-cell-group>
      <div style="margin: 16px; margin-top: 5rem">
        <van-button round block type="primary" native-type="submit">
          确认修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { personalPassword } from '@/api/my/user.js'
import { Notify } from 'vant'
export default {
  name: 'UpdatePassword',
  setup() {
    const store = useStore()

    const usesNumber = computed(() => store.getters.getUserNumber)

    let oldPassword = ref('')

    let newPassword = ref('')

    let confirmPassword = ref('')

    const validator = (val) => /^[a-zA-Z][a-z|0-9|A-Z|.?!#@&^%*,]{5,17}$/.test(val);

    async function onSubmit() {
      if (confirmPassword.value !== newPassword.value) {
        Notify({ type: 'warning', duration: 1000, message: "两次密码输入不一致！" })
        return
      }
      const res = await personalPassword({
        number: usesNumber.value,
        newPassword: newPassword.value,
        oldPassword: oldPassword.value,
      })
      if (res.data.code === 400) {
        Notify({ type: 'warning', duration: 1000, message: res.data.message })
        return
      }
      
      oldPassword.value = ""
      newPassword.value = ""
      confirmPassword.value = ""

      Notify({ type: 'success', duration: 1000, message: '修改成功！' })
    }

    // 点击返回按钮处理函数
    const onClickLeft = () => history.back()

    return {
      oldPassword,
      newPassword,
      confirmPassword,
      onClickLeft,
      onSubmit,
      validator
    }
  },
}
</script>

<style lang="scss" scoped>
  .update-password {
    width: 100%;
    height: 100vh;
    background-color: var(--global-bg);
  }
</style>